<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>python-flask | 茂茂个人博客</title>
    <meta name="generator" content="VuePress 1.7.1">
    <link rel="icon" href="https://pan.zealsay.com/blog/favicon.ico">
    <script>
          var _hmt = _hmt || [];
          (function() {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?b0aae218897fa9d8a9f76e9a77e0b3c6";
            var s = document.getElementsByTagName("script")[0]; 
            s.parentNode.insertBefore(hm, s);
          })();
        </script>
    <meta name="description" content="开心最重要呀">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
    
    <link rel="preload" href="/vue-press-blog-html/assets/css/0.styles.466ff2da.css" as="style"><link rel="preload" href="/vue-press-blog-html/assets/js/app.0c76d487.js" as="script"><link rel="preload" href="/vue-press-blog-html/assets/js/5.12b1c0e9.js" as="script"><link rel="preload" href="/vue-press-blog-html/assets/js/1.6e6d8766.js" as="script"><link rel="preload" href="/vue-press-blog-html/assets/js/21.da88625b.js" as="script"><link rel="prefetch" href="/vue-press-blog-html/assets/js/10.d1650d04.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/11.7dcf07b1.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/12.0f0733e4.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/13.c979057e.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/14.9fb7b8f2.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/15.8ea86eee.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/16.6a2fbcca.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/17.481f1fe6.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/18.8bb85eca.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/19.2c2d2093.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/20.7785d7f0.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/22.283c942f.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/23.f1a0dacf.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/24.1a2dd800.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/25.006a8aa9.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/26.a2a7c588.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/27.ad0f4c12.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/28.bd2020fd.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/29.8dfd8ec0.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/3.3a1f118a.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/30.ffdc92aa.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/31.1869d54d.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/32.1c9db73f.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/33.0d483b05.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/34.3210bba1.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/35.b62e6ca5.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/36.523400ab.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/37.939dfcd0.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/38.455599c3.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/4.70e76d9d.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/6.a759eba0.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/7.0caf748e.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/8.dc1bf2a5.js"><link rel="prefetch" href="/vue-press-blog-html/assets/js/9.5483e0b1.js">
    <link rel="stylesheet" href="/vue-press-blog-html/assets/css/0.styles.466ff2da.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container no-sidebar" data-v-0c5314fc><div data-v-0c5314fc><div id="loader-wrapper" class="loading-wrapper" data-v-d48f4d20 data-v-0c5314fc data-v-0c5314fc><div class="loader-main" data-v-d48f4d20><div data-v-d48f4d20></div><div data-v-d48f4d20></div><div data-v-d48f4d20></div><div data-v-d48f4d20></div></div> <!----> <!----></div> <div class="password-shadow password-wrapper-out" style="display:none;" data-v-5cb9a64e data-v-0c5314fc data-v-0c5314fc><h3 class="title" style="display:none;" data-v-5cb9a64e data-v-5cb9a64e>茂茂个人博客</h3> <!----> <label id="box" class="inputBox" style="display:none;" data-v-5cb9a64e data-v-5cb9a64e><input type="password" value="" data-v-5cb9a64e> <span data-v-5cb9a64e>Konck! Knock!</span> <button data-v-5cb9a64e>OK</button></label> <div class="footer" style="display:none;" data-v-5cb9a64e data-v-5cb9a64e><span data-v-5cb9a64e><i class="iconfont reco-theme" data-v-5cb9a64e></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-5cb9a64e>vuePress-theme-reco</a></span> <span data-v-5cb9a64e><i class="iconfont reco-copyright" data-v-5cb9a64e></i> <a data-v-5cb9a64e><span data-v-5cb9a64e>茂茂</span>
            
          <span data-v-5cb9a64e>2019 - </span>
          2022
        </a></span></div></div> <div class="hide" data-v-0c5314fc><div data-v-0c5314fc><div id="smart" class="wrapper-page" style="background-image:url(/vue-press-blog-html/articleImage/img12.jpeg);background-position-x:center;background-position-y:center;background-size:cover;background-repeat-x:no-repeat;background-repeat-y:no-repeat;" data-v-0c5314fc><header class="navbar" data-v-0c5314fc><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/vue-press-blog-html/" class="home-link router-link-active"><img src="/vue-press-blog-html/logo.png" alt="茂茂个人博客" class="logo"> <span class="site-name">茂茂个人博客</span></a> <div class="links"><div id="dayNightSwitch" class="generalWrapper" data-v-32f44868><a class="click" data-v-32f44868><div class="onOff daySwitch" data-v-32f44868><div class="star star1" data-v-32f44868></div> <div class="star star2" data-v-32f44868></div> <div class="star star3" data-v-32f44868></div> <div class="star star4" data-v-32f44868></div> <div class="star star5" data-v-32f44868></div> <div class="star sky" data-v-32f44868></div> <div class="sunMoon" data-v-32f44868><div class="crater crater1" data-v-32f44868></div> <div class="crater crater2" data-v-32f44868></div> <div class="crater crater3" data-v-32f44868></div> <div class="cloud part1" data-v-32f44868></div> <div class="cloud part2" data-v-32f44868></div></div></div></a></div> <div class="search-box"><i class="iconfont reco-search"></i> <input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/vue-press-blog-html/" class="nav-link"><i class="iconfont reco-home"></i>
  主页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      博客
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/编辑/" class="nav-link"><i class="iconfont undefined"></i>
  编辑
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/vue/" class="nav-link"><i class="iconfont undefined"></i>
  vue
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/工具使用/" class="nav-link"><i class="iconfont undefined"></i>
  工具使用
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/读书/" class="nav-link"><i class="iconfont undefined"></i>
  读书
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/前端/" class="nav-link"><i class="iconfont undefined"></i>
  前端
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/python/" class="nav-link"><i class="iconfont undefined"></i>
  python
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/node/" class="nav-link"><i class="iconfont undefined"></i>
  node
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/可视化/" class="nav-link"><i class="iconfont undefined"></i>
  可视化
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/高德地图/" class="nav-link"><i class="iconfont undefined"></i>
  高德地图
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/ios/" class="nav-link"><i class="iconfont undefined"></i>
  ios
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/react/" class="nav-link"><i class="iconfont undefined"></i>
  react
</a></li></ul></div></div><div class="nav-item"><a href="/vue-press-blog-html/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  标签
</a></div><div class="nav-item"><a href="/vue-press-blog-html/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  时间轴
</a></div><div class="nav-item"><a href="/vue-press-blog-html/about/" class="nav-link"><i class="iconfont reco-account"></i>
  关于
</a></div> <!----></nav></div></header> <div class="sidebar-mask" data-v-0c5314fc></div> <aside class="sidebar" data-v-0c5314fc><div class="personal-info-wrapper" data-v-03833281 data-v-0c5314fc><img src="/vue-press-blog-html/logo.png" alt="author-avatar" class="personal-img" data-v-03833281> <h3 class="name" data-v-03833281>
    茂茂
  </h3> <div class="num" data-v-03833281><div data-v-03833281><h3 data-v-03833281>25</h3> <h6 data-v-03833281>文章</h6></div> <div data-v-03833281><h3 data-v-03833281>21</h3> <h6 data-v-03833281>标签</h6></div></div> <hr data-v-03833281></div> <nav class="nav-links"><div class="nav-item"><a href="/vue-press-blog-html/" class="nav-link"><i class="iconfont reco-home"></i>
  主页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      博客
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/编辑/" class="nav-link"><i class="iconfont undefined"></i>
  编辑
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/vue/" class="nav-link"><i class="iconfont undefined"></i>
  vue
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/工具使用/" class="nav-link"><i class="iconfont undefined"></i>
  工具使用
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/读书/" class="nav-link"><i class="iconfont undefined"></i>
  读书
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/前端/" class="nav-link"><i class="iconfont undefined"></i>
  前端
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/python/" class="nav-link"><i class="iconfont undefined"></i>
  python
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/node/" class="nav-link"><i class="iconfont undefined"></i>
  node
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/可视化/" class="nav-link"><i class="iconfont undefined"></i>
  可视化
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/高德地图/" class="nav-link"><i class="iconfont undefined"></i>
  高德地图
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/ios/" class="nav-link"><i class="iconfont undefined"></i>
  ios
</a></li><li class="dropdown-item"><!----> <a href="/vue-press-blog-html/categories/react/" class="nav-link"><i class="iconfont undefined"></i>
  react
</a></li></ul></div></div><div class="nav-item"><a href="/vue-press-blog-html/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  标签
</a></div><div class="nav-item"><a href="/vue-press-blog-html/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  时间轴
</a></div><div class="nav-item"><a href="/vue-press-blog-html/about/" class="nav-link"><i class="iconfont reco-account"></i>
  关于
</a></div> <!----></nav> <!----> </aside> <div class="password-shadow password-wrapper-in" style="display:none;" data-v-5cb9a64e data-v-0c5314fc><h3 class="title" style="display:none;" data-v-5cb9a64e data-v-5cb9a64e>python-flask</h3> <!----> <label id="box" class="inputBox" style="display:none;" data-v-5cb9a64e data-v-5cb9a64e><input type="password" value="" data-v-5cb9a64e> <span data-v-5cb9a64e>Konck! Knock!</span> <button data-v-5cb9a64e>OK</button></label> <div class="footer" style="display:none;" data-v-5cb9a64e data-v-5cb9a64e><span data-v-5cb9a64e><i class="iconfont reco-theme" data-v-5cb9a64e></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-5cb9a64e>vuePress-theme-reco</a></span> <span data-v-5cb9a64e><i class="iconfont reco-copyright" data-v-5cb9a64e></i> <a data-v-5cb9a64e><span data-v-5cb9a64e>茂茂</span>
            
          <span data-v-5cb9a64e>2019 - </span>
          2022
        </a></span></div></div></div> <div data-v-0c5314fc><main class="page" style="padding-right:0;"><div class="page-title" style="display:none;"><h1 class="title">python-flask</h1> <div class="page-info" data-v-0efa1f05><i class="iconfont reco-account" data-v-0efa1f05><span data-v-0efa1f05>茂茂</span></i> <i class="iconfont reco-date" data-v-0efa1f05><span data-v-0efa1f05>2019-12-15</span></i> <i class="iconfont reco-eye" data-v-0efa1f05><span id="/vue-press-blog-html/blogs/tec/2018/121501.html" data-flag-title="Your Article Title" class="leancloud-visitors" data-v-0efa1f05><a class="leancloud-visitors-count" style="font-size:.9rem;font-weight:normal;color:#999;"></a></span></i> <i class="iconfont reco-tag tags" data-v-0efa1f05><span class="tag-item" data-v-0efa1f05>python</span><span class="tag-item" data-v-0efa1f05>flask</span></i></div></div> <div class="theme-reco-content content__default" style="display:none;"><h2 id="flask"><a href="#flask" class="header-anchor">#</a> flask</h2> <h3 id="路由"><a href="#路由" class="header-anchor">#</a> 路由</h3> <div class="language-python extra-class"><pre class="language-python"><code><span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/'</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">index</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> render_template<span class="token punctuation">(</span><span class="token string">'index.html'</span><span class="token punctuation">)</span>

<span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/article'</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">read</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> render_template<span class="token punctuation">(</span><span class="token string">'article-user.html'</span><span class="token punctuation">)</span>

<span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/user/reg'</span><span class="token punctuation">,</span>methods<span class="token operator">=</span><span class="token punctuation">[</span><span class="token string">'POST'</span><span class="token punctuation">,</span><span class="token string">'GET'</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">register</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> <span class="token string">&quot;good&quot;</span>
<span class="token comment"># 查询参数</span>
<span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/test'</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">test</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    username <span class="token operator">=</span> request<span class="token punctuation">.</span>args<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token string">'username'</span><span class="token punctuation">)</span>
    password <span class="token operator">=</span> request<span class="token punctuation">.</span>args<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token string">'password'</span><span class="token punctuation">)</span>
    <span class="token keyword">return</span> <span class="token string">&quot;你的用户名：%s,密码：%s&quot;</span><span class="token operator">%</span><span class="token punctuation">(</span>username<span class="token punctuation">,</span>password<span class="token punctuation">)</span>
<span class="token comment"># 路由参数地址,加一个int解决参数类型的限制</span>
<span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/article/&lt;int:articleid&gt;-&lt;page&gt;'</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">article</span><span class="token punctuation">(</span>articleid<span class="token punctuation">,</span>page<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> <span class="token string-interpolation"><span class="token string">f&quot;你正在访问编号为：</span><span class="token interpolation"><span class="token punctuation">{</span>articleid<span class="token punctuation">}</span></span><span class="token string">的文章,目前是第</span><span class="token interpolation"><span class="token punctuation">{</span>page<span class="token punctuation">}</span></span><span class="token string">页&quot;</span></span>
<span class="token comment"># post请求正文参数</span>
<span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/user/login'</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">login</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    username <span class="token operator">=</span> request<span class="token punctuation">.</span>form<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token string">'username'</span><span class="token punctuation">)</span>
    password <span class="token operator">=</span> request<span class="token punctuation">.</span>form<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token string">'password'</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> username<span class="token operator">==</span><span class="token string">'wangmaoming'</span> <span class="token keyword">and</span> password<span class="token operator">==</span><span class="token string">'111'</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> <span class="token string">&quot;登陆成功！！！&quot;</span>
    <span class="token keyword">else</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> <span class="token string">&quot;登陆失败&quot;</span>

</code></pre></div><h3 id="restful风格规范"><a href="#restful风格规范" class="header-anchor">#</a> RESTful风格规范</h3> <table><thead><tr><th>接口功能</th> <th>请求类型</th> <th>接口定义</th> <th>备注</th></tr></thead> <tbody><tr><td>查询所有文章</td> <td>GET</td> <td>/article</td> <td>地址只能是/article，不能附加其他内容，例如，/article/all不是有效的RESTful</td></tr> <tr><td>查询一篇文章</td> <td>GET</td> <td>/article/id</td> <td>通过指定文章的id进行查询</td></tr> <tr><td>新增一篇文章</td> <td>POST</td> <td>/article</td> <td>地仍然是/article，没有附加其他内容，非RESTful的地址风格很可能写成/article/add，这个地址没有正确描述资源</td></tr> <tr><td>删除一篇文章</td> <td>DELETE</td> <td>/article/id</td> <td>指定删除哪一篇文章，请勿使用/article/delete/id</td></tr> <tr><td>修改一篇文章</td> <td>PUT</td> <td>/article/id 对某个ID的文章进行更新，更新的数据由PUT请求的正文指定，请勿使用/article/update/id</td> <td></td></tr></tbody></table> <h4 id="满足restful风格的接口地址"><a href="#满足restful风格的接口地址" class="header-anchor">#</a> 满足RESTful风格的接口地址</h4> <div class="language-python extra-class"><pre class="language-python"><code>
<span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/article'</span><span class="token punctuation">,</span>methods<span class="token operator">=</span><span class="token punctuation">[</span><span class="token string">'GET'</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">view</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> <span class="token string">&quot;获取文章&quot;</span>

<span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/article'</span><span class="token punctuation">,</span>methods<span class="token operator">=</span><span class="token punctuation">[</span><span class="token string">'POST'</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">add</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> <span class="token string">&quot;新增文章&quot;</span>

<span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/article/123'</span><span class="token punctuation">,</span>methods<span class="token operator">=</span><span class="token punctuation">[</span><span class="token string">'PUT'</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> <span class="token string">&quot;读取文章&quot;</span>
<span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/article/123'</span><span class="token punctuation">,</span>methods<span class="token operator">=</span><span class="token punctuation">[</span><span class="token string">'DELETE'</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">delete</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> <span class="token string">&quot;删除文章&quot;</span>
</code></pre></div><p>url重定向问题，是HTTP协议本身的功能，重定向302状态码，在响应头里面通过指定location字段告诉浏览器，跳转地址
url_for(&quot;系统里面的函数名&quot;) redirect(url_for('index')) 或者直接用redirect（'/'）</p> <div class="language-python extra-class"><pre class="language-python"><code>
<span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/red'</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">red</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> redirect<span class="token punctuation">(</span><span class="token string">'/'</span><span class="token punctuation">)</span>


<span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/redjs'</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">redjs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    html<span class="token operator">=</span><span class="token string">&quot;感谢访问，2秒之后跳转到首页&quot;</span>
    html<span class="token operator">+=</span><span class="token string">&quot;&lt;script&gt;&quot;</span>
    html<span class="token operator">+=</span><span class="token string">&quot;setTimeout(function(){location.href='/';},2000);&quot;</span>
    html<span class="token operator">+=</span><span class="token string">&quot;&lt;/script&gt;&quot;</span>
    <span class="token keyword">return</span> html
</code></pre></div><h3 id="session-和cookie"><a href="#session-和cookie" class="header-anchor">#</a> session 和cookie</h3> <p>要处理session，必须为app实例设置SECRET_KEY配置参数(app.config['SECRET_KEY']= os.urandom(24))，配置随机数生成器（session id）,再使用session函数进行操作
<a href="https://www.cnblogs.com/XLHIT/p/11171454.html" target="_blank" rel="noopener noreferrer">配置参数<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></p> <p>处理cookie，使用response对象来往http的响应中写入满足http协议的cookie要求信息（key,value,age）
<a href="https://www.cnblogs.com/zhuchunyu/p/10466509.html" target="_blank" rel="noopener noreferrer">response<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></p> <div class="language-python extra-class"><pre class="language-python"><code><span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/sess'</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">sess</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    session<span class="token punctuation">[</span><span class="token string">'username'</span><span class="token punctuation">]</span><span class="token operator">=</span><span class="token string">'wangmaoming'</span>
    session<span class="token punctuation">[</span><span class="token string">'nickname'</span><span class="token punctuation">]</span><span class="token operator">=</span><span class="token string">'wonder'</span>
    <span class="token keyword">return</span> <span class="token string">&quot;存储&quot;</span>
<span class="token comment"># 利用自定义响应的方式来往浏览器设置cookie</span>
<span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/cook'</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">cook</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    response<span class="token operator">=</span>make_response<span class="token punctuation">(</span><span class="token punctuation">)</span>
    response<span class="token punctuation">.</span>set_cookie<span class="token punctuation">(</span><span class="token string">'username'</span><span class="token punctuation">,</span><span class="token string">'wangmaoming'</span><span class="token punctuation">,</span>max_age<span class="token operator">=</span><span class="token number">30</span><span class="token punctuation">)</span>
    response<span class="token punctuation">.</span>set_cookie<span class="token punctuation">(</span><span class="token string">'password'</span><span class="token punctuation">,</span> <span class="token string">'123'</span><span class="token punctuation">,</span> max_age<span class="token operator">=</span><span class="token number">30</span><span class="token punctuation">)</span>
    <span class="token keyword">return</span> response



<span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/sc/read'</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">scread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token comment"># return &quot;你当前名字是：%s&quot;%session.get('username')</span>
    <span class="token keyword">return</span> <span class="token string">&quot;你当前名字是：%s&quot;</span> <span class="token operator">%</span> request<span class="token punctuation">.</span>cookies<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token string">'username'</span><span class="token punctuation">)</span>
</code></pre></div><h3 id="mvc模型"><a href="#mvc模型" class="header-anchor">#</a> MVC模型</h3> <p><img src="/MVCmodel@2x.png" alt="alt 视图控制器02" title="视图控制器02"></p> <h3 id="模块化与拦截器"><a href="#模块化与拦截器" class="header-anchor">#</a> 模块化与拦截器</h3> <p>使用Blueprint蓝图对路由进行模块化处理
1.入口文件注册蓝图</p> <div class="language-python extra-class"><pre class="language-python"><code><span class="token comment"># 注册蓝图</span>
app<span class="token punctuation">.</span>register_blueprint<span class="token punctuation">(</span>demo<span class="token punctuation">)</span>
</code></pre></div><p>2.模块话的文件里面使用蓝图</p> <div class="language-python extra-class"><pre class="language-python"><code><span class="token keyword">from</span> flask <span class="token keyword">import</span> Blueprint
demo<span class="token operator">=</span>Blueprint<span class="token punctuation">(</span><span class="token string">'demo'</span><span class="token punctuation">,</span>__name__<span class="token punctuation">)</span>

<span class="token decorator annotation punctuation">@demo<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/demo'</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">onedemo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> <span class="token string">&quot;蓝图设置模块化&quot;</span>
</code></pre></div><h3 id="python的代码主要分为三层"><a href="#python的代码主要分为三层" class="header-anchor">#</a> python的代码主要分为三层</h3> <p>1.包（含有__init__.py的文件夹）
2.模块（包下面的.py的源代码/源文件）
3.类class ， 函数，全局变量</p> <h3 id="拦截器"><a href="#拦截器" class="header-anchor">#</a> 拦截器</h3> <p>对接口请求进行预先处理，然后交由控制器处理，说白了就是在客户端与服务器控制器中间加了一个拦截器用于审核。</p> <h4 id="全局拦截器"><a href="#全局拦截器" class="header-anchor">#</a> 全局拦截器</h4> <p>应用于flask实例（app.py）中，对所有经过当前系统的请求进行拦截检查
a)全局拦截器，要设置好白名单，让无需检验的接口正常访问
b)全局拦截器，由于会检查每一个请求，所以会导致性能的下降，尽量少用</p> <div class="language-python extra-class"><pre class="language-python"><code><span class="token comment"># 拦截器</span>
<span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>before_request</span>
<span class="token keyword">def</span> <span class="token function">before</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    url <span class="token operator">=</span> request<span class="token punctuation">.</span>path
    <span class="token keyword">if</span> url <span class="token operator">==</span> <span class="token string">'/sess'</span><span class="token punctuation">:</span>
        <span class="token keyword">pass</span>
    <span class="token comment">#     如果用户登陆session['islogin'] = 'true'，不拦截</span>
    <span class="token keyword">elif</span> session<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token string">'islogin'</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token string">'true'</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> <span class="token string">&quot;没有登陆无法访问&quot;</span>
    <span class="token keyword">else</span><span class="token punctuation">:</span>
        <span class="token keyword">pass</span>
<span class="token comment"># 拦截器可以搞一个白名单，就是可以不用验证就通过</span>
    pass_list<span class="token operator">=</span><span class="token punctuation">[</span><span class="token string">'/'</span><span class="token punctuation">,</span><span class="token string">'/reg'</span><span class="token punctuation">,</span><span class="token string">'/login'</span><span class="token punctuation">,</span><span class="token string">'/vcode'</span><span class="token punctuation">,</span><span class="token string">'/sess'</span><span class="token punctuation">]</span>
    suffix<span class="token operator">=</span>url<span class="token punctuation">.</span>endswith<span class="token punctuation">(</span><span class="token string">'.png'</span><span class="token punctuation">)</span><span class="token keyword">or</span> url<span class="token punctuation">.</span>endswith<span class="token punctuation">(</span><span class="token string">'.jpg'</span><span class="token keyword">or</span> url<span class="token punctuation">.</span>endswith<span class="token punctuation">(</span><span class="token string">'.css'</span><span class="token punctuation">)</span><span class="token keyword">or</span> url<span class="token punctuation">.</span>endswith<span class="token punctuation">(</span><span class="token string">'.js'</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> url <span class="token keyword">in</span> pass_list <span class="token keyword">or</span> suffix<span class="token punctuation">:</span>
        <span class="token keyword">pass</span>
    <span class="token keyword">else</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> <span class="token string">&quot;开始实现拦截&quot;</span>
</code></pre></div><h4 id="控制器拦截器-模块拦截器"><a href="#控制器拦截器-模块拦截器" class="header-anchor">#</a> 控制器拦截器（模块拦截器）</h4> <p>只针对某个模块进行拦截，应用于blueprint模块</p> <div class="language-python extra-class"><pre class="language-python"><code><span class="token keyword">from</span> flask <span class="token keyword">import</span> Blueprint<span class="token punctuation">,</span> request

demo<span class="token operator">=</span>Blueprint<span class="token punctuation">(</span><span class="token string">'demo'</span><span class="token punctuation">,</span>__name__<span class="token punctuation">)</span>
<span class="token comment"># 定义一个模块拦截器</span>
<span class="token decorator annotation punctuation">@demo<span class="token punctuation">.</span>before_request</span>
<span class="token keyword">def</span> <span class="token function">demo_before</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    url <span class="token operator">=</span> request<span class="token punctuation">.</span>path
    <span class="token keyword">if</span> url <span class="token operator">==</span> <span class="token string">'/demo1'</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> <span class="token string">&quot;无法访问&quot;</span>

<span class="token decorator annotation punctuation">@demo<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/demo1'</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">onedemo1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> <span class="token string">&quot;蓝图设置模块化1&quot;</span>

<span class="token decorator annotation punctuation">@demo<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/demo2'</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">onedemo2</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> <span class="token string">&quot;蓝图设置模块化2&quot;</span>
</code></pre></div><h3 id="模版引擎-jinja2"><a href="#模版引擎-jinja2" class="header-anchor">#</a> 模版引擎-Jinja2</h3> <p><a href="https://blog.csdn.net/u011146423/article/details/84314335" target="_blank" rel="noopener noreferrer">看这个就够了<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></p> <h3 id="pymysql"><a href="#pymysql" class="header-anchor">#</a> pymysql</h3> <div class="language-python extra-class"><pre class="language-python"><code><span class="token keyword">import</span> pymysql

<span class="token comment"># 所有的i/o操作：文件，数据库，网络等均有下面三步操作</span>
<span class="token comment"># 1连接数据库.</span>
conn<span class="token operator">=</span>pymysql<span class="token punctuation">.</span>connect<span class="token punctuation">(</span>host<span class="token operator">=</span><span class="token string">'127.0.0.1'</span><span class="token punctuation">,</span>port<span class="token operator">=</span><span class="token number">3306</span><span class="token punctuation">,</span>user<span class="token operator">=</span><span class="token string">'root'</span><span class="token punctuation">,</span>password<span class="token operator">=</span><span class="token string">'wangmaoming218'</span><span class="token punctuation">,</span>charset<span class="token operator">=</span><span class="token string">'utf8'</span><span class="token punctuation">,</span>database<span class="token operator">=</span><span class="token string">'woniunote'</span><span class="token punctuation">,</span>autocommit<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span>
<span class="token comment"># 2执行sql语句</span>
<span class="token comment"># a.实例话一个游标对象，</span>
cursor<span class="token operator">=</span>conn<span class="token punctuation">.</span>cursor<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment"># b.定义sql语句</span>
<span class="token comment"># sql=&quot;select * from users&quot;</span>
<span class="token comment"># #c.通过游标执行</span>
<span class="token comment"># cursor.execute(sql)</span>
<span class="token comment"># # d.处理执行结果</span>
<span class="token comment"># result=cursor.fetchall()</span>
<span class="token comment"># for row in result:</span>
<span class="token comment">#     print(row[6])</span>
<span class="token comment"># print(result)</span>
<span class="token comment">#   更新</span>
sql<span class="token operator">=</span><span class="token string">&quot;update users set qq='1072445948' where userid=2&quot;</span>
cursor<span class="token punctuation">.</span>execute<span class="token punctuation">(</span>sql<span class="token punctuation">)</span>
<span class="token comment"># 提交修改 update,insert,delete</span>
<span class="token comment"># conn.commit()</span>
<span class="token comment"># 关闭数据库连接</span>
cursor<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">#关闭游标</span>
conn<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">#关闭数据库对象</span>

</code></pre></div><h3 id="魔术方法-name"><a href="#魔术方法-name" class="header-anchor">#</a> 魔术方法（<strong>name</strong>）</h3> <div class="language-python extra-class"><pre class="language-python"><code><span class="token keyword">class</span> <span class="token class-name">User</span><span class="token punctuation">:</span>
    table_name<span class="token operator">=</span><span class="token string">'users'</span>  <span class="token comment">#类属性</span>

    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>username<span class="token operator">=</span><span class="token string">'wangmaoming'</span> <span class="token comment">#实例变量</span>
        self<span class="token punctuation">.</span>password <span class="token operator">=</span> <span class="token string">'123'</span>
        self<span class="token punctuation">.</span>email <span class="token operator">=</span> <span class="token string">'1072445948@qq.com'</span>
    <span class="token keyword">def</span> <span class="token function">method</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span>value<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">&quot;hello %s&quot;</span> <span class="token operator">%</span> value<span class="token punctuation">)</span>
    <span class="token comment">#     链式操作</span>
    <span class="token keyword">def</span> <span class="token function">chain</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">&quot;通过返回当前类的实例进行连续的方法调用&quot;</span><span class="token punctuation">)</span>
        <span class="token keyword">return</span> self
    <span class="token keyword">def</span> <span class="token function">hello</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">&quot;hello in chain&quot;</span><span class="token punctuation">)</span>
        <span class="token keyword">return</span> self
<span class="token keyword">if</span> __name__<span class="token operator">==</span><span class="token string">'__main__'</span><span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>User<span class="token punctuation">.</span>__dict__<span class="token punctuation">)</span> <span class="token comment">#通过类名可以直接获取到类的属性和方法</span>
    user<span class="token operator">=</span>User<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">#实例化User类</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>user<span class="token punctuation">.</span>__class__<span class="token punctuation">)</span> <span class="token comment">#通过实例可以获取到对应的类   &lt;class '__main__.User'&gt;</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>user<span class="token punctuation">.</span>__class__<span class="token punctuation">.</span>__dict__<span class="token punctuation">)</span>

<span class="token comment">#     通过__来区分哪些是自定义属性和方法，一般没有__的是自定义的</span>
    <span class="token keyword">for</span> k<span class="token punctuation">,</span> v <span class="token keyword">in</span> User<span class="token punctuation">.</span>__dict__<span class="token punctuation">.</span>items<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">if</span> <span class="token keyword">not</span> k<span class="token punctuation">.</span>startswith<span class="token punctuation">(</span><span class="token string">'__'</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
            <span class="token keyword">print</span><span class="token punctuation">(</span>k<span class="token punctuation">,</span>v<span class="token punctuation">)</span>  <span class="token comment">#table_name users   method &lt;function User.method at 0x7fdbec9aa050&gt;</span>

    <span class="token keyword">print</span><span class="token punctuation">(</span>User<span class="token punctuation">.</span>__name__<span class="token punctuation">)</span>  <span class="token comment">#User</span>

    <span class="token keyword">print</span><span class="token punctuation">(</span>user<span class="token punctuation">.</span>__dict__<span class="token punctuation">)</span>  <span class="token comment">#获取实例变量或属性 {'username': 'wangmaoming', 'password': '123', 'email': '1072445948@qq.com'}</span>

    <span class="token comment"># user.nickname='小王'</span>
    <span class="token comment"># print(user.__dict__) #添加实例属性{'username': 'wangmaoming', 'password': '123', 'email': '1072445948@qq.com', 'nickname': '小王'}</span>
    <span class="token comment"># __setattr__魔术方法</span>
    user<span class="token punctuation">.</span>__setattr__<span class="token punctuation">(</span><span class="token string">'nickname'</span><span class="token punctuation">,</span><span class="token string">'小王'</span><span class="token punctuation">)</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>user<span class="token punctuation">.</span>__dict__<span class="token punctuation">)</span>  <span class="token comment">#加实例属性{'username': 'wangmaoming', 'password': '123', 'email': '1072445948@qq.com', 'nickname': '小王'}</span>
    <span class="token comment"># 全局函数一样可以</span>
    <span class="token builtin">setattr</span><span class="token punctuation">(</span>user<span class="token punctuation">,</span><span class="token string">'nickname'</span><span class="token punctuation">,</span><span class="token string">'小王'</span><span class="token punctuation">)</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>user<span class="token punctuation">.</span>__dict__<span class="token punctuation">)</span>

    <span class="token keyword">print</span><span class="token punctuation">(</span>user<span class="token punctuation">.</span>__getattribute__<span class="token punctuation">(</span><span class="token string">'nickname'</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment">#小王</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>user<span class="token punctuation">.</span>__getattribute__<span class="token punctuation">(</span><span class="token string">'method'</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    user<span class="token punctuation">.</span>__getattribute__<span class="token punctuation">(</span><span class="token string">'method'</span><span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token string">'成都'</span><span class="token punctuation">)</span>   <span class="token comment">#hello 成都</span>

    <span class="token builtin">getattr</span><span class="token punctuation">(</span>user<span class="token punctuation">,</span><span class="token string">'method'</span><span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token string">'北京'</span><span class="token punctuation">)</span>  <span class="token comment">#hello 北京</span>
    <span class="token comment"># 链式操作</span>
    user<span class="token punctuation">.</span>chain<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>chain<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>hello<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>chain<span class="token punctuation">(</span><span class="token punctuation">)</span>
</code></pre></div><h3 id="自定义orm框架"><a href="#自定义orm框架" class="header-anchor">#</a> 自定义ORM框架</h3> <ol><li>ORM(Object-Relational Mapping)对象-关系映射，把数据转换成python对象，与python无关，想Java，C都有。
这样就能实现对数据库的操作对象化，减少或者不用编写sql原生语句</li> <li>数据库重的表 -&gt; python 的类</li> <li>表中的列 -&gt; 类的属性</li> <li>表里面的行 -&gt;类的实例，字典对象表述</li> <li>字典对象的key对应列，value对应值</li> <li>对增删改查进行封装，</li></ol> <div class="language-python extra-class"><pre class="language-python"><code><span class="token keyword">import</span> pymysql
<span class="token keyword">from</span> pymysql<span class="token punctuation">.</span>cursors <span class="token keyword">import</span> DictCursor


<span class="token keyword">class</span> <span class="token class-name">MySQL</span><span class="token punctuation">:</span>
    <span class="token comment"># 实例话，创建与数据库之间的连接</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        conn <span class="token operator">=</span> pymysql<span class="token punctuation">.</span>connect<span class="token punctuation">(</span>host<span class="token operator">=</span><span class="token string">'127.0.0.1'</span><span class="token punctuation">,</span> port<span class="token operator">=</span><span class="token number">3306</span><span class="token punctuation">,</span> user<span class="token operator">=</span><span class="token string">'root'</span><span class="token punctuation">,</span> password<span class="token operator">=</span><span class="token string">'wangmaoming218'</span><span class="token punctuation">,</span>
                               charset<span class="token operator">=</span><span class="token string">'utf8'</span><span class="token punctuation">,</span> database<span class="token operator">=</span><span class="token string">'woniunote'</span><span class="token punctuation">,</span> autocommit<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>cursor <span class="token operator">=</span> conn<span class="token punctuation">.</span>cursor<span class="token punctuation">(</span>DictCursor<span class="token punctuation">)</span>

    <span class="token comment"># 查询</span>
    <span class="token keyword">def</span> <span class="token function">query</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> sql<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>cursor<span class="token punctuation">.</span>execute<span class="token punctuation">(</span>sql<span class="token punctuation">)</span>
        result <span class="token operator">=</span> self<span class="token punctuation">.</span>cursor<span class="token punctuation">.</span>fetchall<span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token keyword">return</span> result

    <span class="token keyword">def</span> <span class="token function">execute</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> sql<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">try</span><span class="token punctuation">:</span>
            self<span class="token punctuation">.</span>cursor<span class="token punctuation">.</span>execute<span class="token punctuation">(</span>sql<span class="token punctuation">)</span>
            <span class="token keyword">return</span> <span class="token string">'ok'</span>
        <span class="token keyword">except</span><span class="token punctuation">:</span>
            <span class="token keyword">return</span> <span class="token string">'fail'</span>


<span class="token keyword">class</span> <span class="token class-name">Model</span><span class="token punctuation">:</span>
    <span class="token comment"># 构造方法，传字典参数作为insert的key,value</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> <span class="token operator">**</span>kwargs<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">for</span> k<span class="token punctuation">,</span> v <span class="token keyword">in</span> kwargs<span class="token punctuation">.</span>items<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
            self<span class="token punctuation">.</span>__setattr__<span class="token punctuation">(</span>k<span class="token punctuation">,</span> v<span class="token punctuation">)</span>
<span class="token comment">#     通过链式操作指定查询哪些列</span>
    <span class="token keyword">def</span> <span class="token function">field</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span>columns<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>columns <span class="token operator">=</span>columns <span class="token comment">#动态增加类实例属性</span>
        <span class="token keyword">return</span> self
    <span class="token comment"># 带列名查询条件</span>
    <span class="token keyword">def</span> <span class="token function">select</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> <span class="token operator">**</span>where<span class="token punctuation">)</span><span class="token punctuation">:</span>
        table<span class="token operator">=</span>self<span class="token punctuation">.</span>__class__<span class="token punctuation">.</span>__getattribute__<span class="token punctuation">(</span>self<span class="token punctuation">,</span><span class="token string">'table_name'</span><span class="token punctuation">)</span>
        <span class="token keyword">if</span> <span class="token builtin">hasattr</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span><span class="token string">'columns'</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
            sql <span class="token operator">=</span> <span class="token string">&quot;select %s from %s &quot;</span> <span class="token operator">%</span> <span class="token punctuation">(</span>self<span class="token punctuation">.</span>columns<span class="token punctuation">,</span>table<span class="token punctuation">)</span>
        <span class="token keyword">else</span><span class="token punctuation">:</span>
            sql <span class="token operator">=</span> <span class="token string">&quot;select * from %s &quot;</span> <span class="token operator">%</span>  table
        <span class="token keyword">if</span> where <span class="token keyword">is</span> <span class="token keyword">not</span> <span class="token boolean">None</span><span class="token punctuation">:</span>
            sql <span class="token operator">+=</span> <span class="token string">&quot;where&quot;</span>
            <span class="token keyword">for</span> k<span class="token punctuation">,</span> v <span class="token keyword">in</span> where<span class="token punctuation">.</span>items<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
                sql <span class="token operator">+=</span> <span class="token string">&quot; %s='%s' and&quot;</span> <span class="token operator">%</span> <span class="token punctuation">(</span>k<span class="token punctuation">,</span> v<span class="token punctuation">)</span>
            sql <span class="token operator">+=</span> <span class="token string">' 1=1'</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span>sql<span class="token punctuation">)</span>
        result <span class="token operator">=</span> MySQL<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>query<span class="token punctuation">(</span>sql<span class="token punctuation">)</span>
        <span class="token keyword">return</span> result
<span class="token comment">#     封装新增：insert into table(c1,c2) values(v1,v2)</span>
    <span class="token keyword">def</span> <span class="token function">insert</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        keys<span class="token operator">=</span><span class="token punctuation">[</span><span class="token punctuation">]</span>
        values<span class="token operator">=</span><span class="token punctuation">[</span><span class="token punctuation">]</span>
        <span class="token keyword">for</span> k <span class="token punctuation">,</span>v <span class="token keyword">in</span> self<span class="token punctuation">.</span>__dict__<span class="token punctuation">.</span>items<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
            keys<span class="token punctuation">.</span>append<span class="token punctuation">(</span>k<span class="token punctuation">)</span>
            values<span class="token punctuation">.</span>append<span class="token punctuation">(</span><span class="token builtin">str</span><span class="token punctuation">(</span>v<span class="token punctuation">)</span><span class="token punctuation">)</span>
        sql <span class="token operator">=</span> <span class="token string">&quot;insert into %s(%s) value ('%s')&quot;</span> <span class="token operator">%</span><span class="token punctuation">(</span>self<span class="token punctuation">.</span>table_name<span class="token punctuation">,</span><span class="token string">','</span><span class="token punctuation">.</span>join<span class="token punctuation">(</span>keys<span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token string">&quot;','&quot;</span><span class="token punctuation">.</span>join<span class="token punctuation">(</span>values<span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span>sql<span class="token punctuation">)</span>
        result <span class="token operator">=</span> MySQL<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>query<span class="token punctuation">(</span>sql<span class="token punctuation">)</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span>

<span class="token keyword">class</span> <span class="token class-name">User</span><span class="token punctuation">(</span>Model<span class="token punctuation">)</span><span class="token punctuation">:</span>
    table_name<span class="token operator">=</span><span class="token string">'users'</span>
<span class="token comment">#     调用父类的构造方法</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span><span class="token operator">**</span>kwargs<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token builtin">super</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>__init__<span class="token punctuation">(</span><span class="token operator">**</span>kwargs<span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">Article</span><span class="token punctuation">(</span>Model<span class="token punctuation">)</span><span class="token punctuation">:</span>
    table_name<span class="token operator">=</span><span class="token string">'article'</span>
<span class="token comment">#     调用父类的构造方法</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span><span class="token operator">**</span>kwargs<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token builtin">super</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>__init__<span class="token punctuation">(</span><span class="token operator">**</span>kwargs<span class="token punctuation">)</span>

user <span class="token operator">=</span>User<span class="token punctuation">(</span><span class="token punctuation">)</span>
result<span class="token operator">=</span>user<span class="token punctuation">.</span>field<span class="token punctuation">(</span><span class="token string">'userid,username'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>select<span class="token punctuation">(</span>userid<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span>

<span class="token comment"># class User:</span>
<span class="token comment">#     table_name = 'users'  # 定义表名</span>
<span class="token comment">#</span>
<span class="token comment">#     # 构造方法，传字典参数作为insert的key,value</span>
<span class="token comment">#     def __init__(self, **kwargs):</span>
<span class="token comment">#         for k, v in kwargs.items():</span>
<span class="token comment">#             self.__setattr__(k, v)</span>
<span class="token comment">#</span>
<span class="token comment">#     #  **字典参数</span>
<span class="token comment">#     def select(self, **where):</span>
<span class="token comment">#         sql = &quot;select * from %s &quot; % self.table_name</span>
<span class="token comment">#         if where is not None:</span>
<span class="token comment">#             sql += &quot;where&quot;</span>
<span class="token comment">#             for k, v in where.items():</span>
<span class="token comment">#                 sql += &quot; %s='%s' and&quot; % (k, v)</span>
<span class="token comment">#             sql += ' 1=1'</span>
<span class="token comment">#         print(sql)</span>
<span class="token comment">#         result = MySQL().query(sql)</span>
<span class="token comment">#         return result</span>
<span class="token comment">#</span>
<span class="token comment"># #     封装新增：insert into table(c1,c2) values(v1,v2)</span>
<span class="token comment">#     def insert(self):</span>
<span class="token comment">#         keys=[]</span>
<span class="token comment">#         values=[]</span>
<span class="token comment">#         for k ,v in self.__dict__.items():</span>
<span class="token comment">#             keys.append(k)</span>
<span class="token comment">#             values.append(str(v))</span>
<span class="token comment">#         sql = &quot;insert into %s(%s) value ('%s')&quot; %(self.table_name,','.join(keys),&quot;','&quot;.join(values))</span>
<span class="token comment">#         print(sql)</span>
<span class="token comment">#         result = MySQL().query(sql)</span>
<span class="token comment">#         print(result)</span>

<span class="token comment"># if __name__ == '__main__':</span>
<span class="token comment">#     # user = User()</span>
<span class="token comment">#     # result = user.select(userid=2, nickname='sad')</span>
<span class="token comment">#     # print(result)</span>
<span class="token comment">#     user =User(username='wmm',password='123',role='user',credit='50')</span>
<span class="token comment">#     user.insert()</span>

</code></pre></div><h3 id="sqlalchemy"><a href="#sqlalchemy" class="header-anchor">#</a> SQLAlchemy</h3> <p>数据库连接以及通过代码创建一个userx表。如果数据库已经创建好了没必要又写在代码中。</p> <div class="language-python extra-class"><pre class="language-python"><code><span class="token comment"># 建立与mysql的连接</span>
<span class="token keyword">from</span> sqlalchemy <span class="token keyword">import</span> create_engine<span class="token punctuation">,</span> Column<span class="token punctuation">,</span> Integer<span class="token punctuation">,</span> String<span class="token punctuation">,</span> DateTime
<span class="token keyword">from</span> sqlalchemy<span class="token punctuation">.</span>ext<span class="token punctuation">.</span>declarative <span class="token keyword">import</span> declarative_base
<span class="token keyword">from</span> sqlalchemy<span class="token punctuation">.</span>orm <span class="token keyword">import</span> sessionmaker<span class="token punctuation">,</span> session<span class="token punctuation">,</span> scoped_session

engine <span class="token operator">=</span>create_engine<span class="token punctuation">(</span><span class="token string">'mysql+pymysql://root:wangmaoming218@localhost/woniunote'</span><span class="token punctuation">)</span>

<span class="token comment"># 定义模型类继承的父类及数据连接会话</span>
DBsession<span class="token operator">=</span>sessionmaker<span class="token punctuation">(</span>bind<span class="token operator">=</span>engine<span class="token punctuation">)</span>
dbsession<span class="token operator">=</span>scoped_session<span class="token punctuation">(</span>DBsession<span class="token punctuation">)</span>  <span class="token comment">#线程安全的scoped_session</span>
Base<span class="token operator">=</span>declarative_base<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment">#定义模型类</span>
<span class="token keyword">class</span> <span class="token class-name">Users</span><span class="token punctuation">(</span>Base<span class="token punctuation">)</span><span class="token punctuation">:</span>
    __tablename__ <span class="token operator">=</span><span class="token string">&quot;userx&quot;</span>
<span class="token comment">#     假如数据库没有去创建表，我们可以在这里通过代码创建，如果需要在SQLAlchemy里面直接创建表结构，则详细定义列</span>
    userid <span class="token operator">=</span>Column<span class="token punctuation">(</span>Integer<span class="token punctuation">,</span>primary_key<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span>
    username<span class="token operator">=</span>Column<span class="token punctuation">(</span>String<span class="token punctuation">(</span><span class="token number">50</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    password <span class="token operator">=</span> Column<span class="token punctuation">(</span>String<span class="token punctuation">(</span><span class="token number">32</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    nickname <span class="token operator">=</span> Column<span class="token punctuation">(</span>String<span class="token punctuation">(</span><span class="token number">30</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    qq <span class="token operator">=</span> Column<span class="token punctuation">(</span>String<span class="token punctuation">(</span><span class="token number">15</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    role <span class="token operator">=</span> Column<span class="token punctuation">(</span>String<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    credit <span class="token operator">=</span> Column<span class="token punctuation">(</span>Integer<span class="token punctuation">)</span>
    createtime <span class="token operator">=</span> Column<span class="token punctuation">(</span>DateTime<span class="token punctuation">)</span>
    updatetime <span class="token operator">=</span> Column<span class="token punctuation">(</span>DateTime<span class="token punctuation">)</span>

<span class="token comment"># 创建表</span>
Users<span class="token punctuation">.</span>metadata<span class="token punctuation">.</span>create_all<span class="token punctuation">(</span>engine<span class="token punctuation">)</span>

</code></pre></div><p>独立的SQLAlchemy数据库操作</p> <div class="language-python extra-class"><pre class="language-python"><code><span class="token comment"># 建立与mysql的连接</span>
<span class="token keyword">from</span> sqlalchemy <span class="token keyword">import</span> create_engine<span class="token punctuation">,</span> Column<span class="token punctuation">,</span> Integer<span class="token punctuation">,</span> String<span class="token punctuation">,</span> DateTime<span class="token punctuation">,</span> MetaData<span class="token punctuation">,</span> Table
<span class="token keyword">from</span> sqlalchemy<span class="token punctuation">.</span>ext<span class="token punctuation">.</span>declarative <span class="token keyword">import</span> declarative_base
<span class="token keyword">from</span> sqlalchemy<span class="token punctuation">.</span>orm <span class="token keyword">import</span> sessionmaker<span class="token punctuation">,</span> session<span class="token punctuation">,</span> scoped_session

engine <span class="token operator">=</span> create_engine<span class="token punctuation">(</span><span class="token string">'mysql+pymysql://root:wangmaoming218@localhost/woniunote'</span><span class="token punctuation">)</span>

<span class="token comment"># 定义模型类继承的父类及数据连接会话</span>
DBsession <span class="token operator">=</span> sessionmaker<span class="token punctuation">(</span>bind<span class="token operator">=</span>engine<span class="token punctuation">)</span>
dbsession <span class="token operator">=</span> scoped_session<span class="token punctuation">(</span>DBsession<span class="token punctuation">)</span>  <span class="token comment"># 线程安全的scoped_session</span>
Base <span class="token operator">=</span> declarative_base<span class="token punctuation">(</span><span class="token punctuation">)</span>
md <span class="token operator">=</span> MetaData<span class="token punctuation">(</span>bind<span class="token operator">=</span>engine<span class="token punctuation">)</span>


<span class="token comment"># 定义模型类</span>
<span class="token comment"># class Users(Base):</span>
<span class="token comment">#     __tablename__ =&quot;userx&quot;</span>
<span class="token comment"># #     假如数据库没有去创建表，我们可以在这里通过代码创建，如果需要在SQLAlchemy里面直接创建表结构，则详细定义列</span>
<span class="token comment">#     userid =Column(Integer,primary_key=True)</span>
<span class="token comment">#     username=Column(String(50))</span>
<span class="token comment">#     password = Column(String(32))</span>
<span class="token comment">#     nickname = Column(String(30))</span>
<span class="token comment">#     qq = Column(String(15))</span>
<span class="token comment">#     role = Column(String(10))</span>
<span class="token comment">#     credit = Column(Integer)</span>
<span class="token comment">#     createtime = Column(DateTime)</span>
<span class="token comment">#     updatetime = Column(DateTime)</span>
<span class="token comment">#</span>
<span class="token comment"># # 创建表</span>
<span class="token comment"># Users.metadata.create_all(engine)</span>

<span class="token keyword">class</span> <span class="token class-name">Users</span><span class="token punctuation">(</span>Base<span class="token punctuation">)</span><span class="token punctuation">:</span>
    __table__ <span class="token operator">=</span> Table<span class="token punctuation">(</span><span class="token string">'users'</span><span class="token punctuation">,</span> md<span class="token punctuation">,</span> autoload<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span>

<span class="token keyword">class</span> <span class="token class-name">Article</span><span class="token punctuation">(</span>Base<span class="token punctuation">)</span><span class="token punctuation">:</span>
    __table__ <span class="token operator">=</span> Table<span class="token punctuation">(</span><span class="token string">'article'</span><span class="token punctuation">,</span> md<span class="token punctuation">,</span> autoload<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span>

<span class="token keyword">if</span> __name__ <span class="token operator">==</span> <span class="token string">'__main__'</span><span class="token punctuation">:</span>
    <span class="token comment"># result=dbsession.query(Users).filter(Users.userid&gt;2).all()</span>
    result <span class="token operator">=</span> dbsession<span class="token punctuation">.</span>query<span class="token punctuation">(</span>Users<span class="token punctuation">)</span><span class="token punctuation">.</span>filter_by<span class="token punctuation">(</span>userid<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">all</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">for</span> row <span class="token keyword">in</span> result<span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span>row<span class="token punctuation">.</span>userid<span class="token punctuation">)</span>

    row <span class="token operator">=</span>dbsession<span class="token punctuation">.</span>query<span class="token punctuation">(</span>Users<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">filter</span><span class="token punctuation">(</span>Users<span class="token punctuation">.</span>userid<span class="token operator">&lt;</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">.</span>first<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>row<span class="token punctuation">)</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>row<span class="token punctuation">.</span>userid<span class="token punctuation">,</span>row<span class="token punctuation">.</span>username<span class="token punctuation">)</span>

    row <span class="token operator">=</span> dbsession<span class="token punctuation">.</span>query<span class="token punctuation">(</span>Users<span class="token punctuation">.</span>userid<span class="token punctuation">,</span>Users<span class="token punctuation">.</span>username<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">filter</span><span class="token punctuation">(</span>Users<span class="token punctuation">.</span>userid <span class="token operator">&lt;</span> <span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">.</span>first<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>row<span class="token punctuation">)</span>

<span class="token comment">#     新增</span>
<span class="token comment">#     user =Users(username='wmm1',password='123',role='user',credit='50')</span>
<span class="token comment">#     dbsession.add(user)</span>
<span class="token comment">#     dbsession.commit()   #手动提交</span>

<span class="token comment">#     更新，需要查询出来要修改的行，再进行修改</span>
<span class="token comment">#     row=dbsession.query(Users).filter_by(userid=4).first()</span>
<span class="token comment">#     row.username='daskdas'</span>
<span class="token comment">#     dbsession.commit()</span>

    row<span class="token operator">=</span>dbsession<span class="token punctuation">.</span>query<span class="token punctuation">(</span>Users<span class="token punctuation">)</span><span class="token punctuation">.</span>filter_by<span class="token punctuation">(</span>userid<span class="token operator">=</span><span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">.</span>delete<span class="token punctuation">(</span><span class="token punctuation">)</span>
    dbsession<span class="token punctuation">.</span>commit<span class="token punctuation">(</span><span class="token punctuation">)</span>

</code></pre></div><h3 id="flask-sqlalchemy-flask集成sqlalchemy"><a href="#flask-sqlalchemy-flask集成sqlalchemy" class="header-anchor">#</a> flask_sqlalchemy(flask集成SQLAlchemy)</h3> <p>第一步在main.py文件连接数据库并实例话db对象</p> <div class="language-python extra-class"><pre class="language-python"><code><span class="token keyword">from</span> flask <span class="token keyword">import</span> Flask<span class="token punctuation">,</span> render_template<span class="token punctuation">,</span> request<span class="token punctuation">,</span> url_for<span class="token punctuation">,</span> redirect<span class="token punctuation">,</span> session<span class="token punctuation">,</span> make_response
<span class="token keyword">import</span> os

<span class="token keyword">from</span> flask_sqlalchemy <span class="token keyword">import</span> SQLAlchemy
<span class="token keyword">import</span> pymysql
pymysql<span class="token punctuation">.</span>install_as_MySQLdb<span class="token punctuation">(</span><span class="token punctuation">)</span>


app <span class="token operator">=</span> Flask<span class="token punctuation">(</span>__name__<span class="token punctuation">,</span> template_folder<span class="token operator">=</span><span class="token string">'template'</span><span class="token punctuation">,</span> static_url_path<span class="token operator">=</span><span class="token string">'/'</span><span class="token punctuation">,</span> static_folder<span class="token operator">=</span><span class="token string">'resource'</span><span class="token punctuation">,</span> <span class="token punctuation">)</span>
app<span class="token punctuation">.</span>config<span class="token punctuation">[</span><span class="token string">'SECRET_KEY'</span><span class="token punctuation">]</span> <span class="token operator">=</span> os<span class="token punctuation">.</span>urandom<span class="token punctuation">(</span><span class="token number">24</span><span class="token punctuation">)</span>
<span class="token comment"># 使用集成方式处理SQLAlchemy</span>
app<span class="token punctuation">.</span>config<span class="token punctuation">[</span><span class="token string">'SQLALCHEMY_DATABASE_URI'</span><span class="token punctuation">]</span><span class="token operator">=</span><span class="token string">'mysql://root:wangmaoming218@localhost/woniunote?charset=utf8'</span>
app<span class="token punctuation">.</span>config<span class="token punctuation">[</span><span class="token string">'SQLALCHEMY_TRACK_MODIFICATIONS'</span><span class="token punctuation">]</span><span class="token operator">=</span><span class="token boolean">False</span>
<span class="token comment"># 实例话db对象</span>
db<span class="token operator">=</span>SQLAlchemy<span class="token punctuation">(</span>app<span class="token punctuation">)</span>


<span class="token keyword">if</span> __name__ <span class="token operator">==</span> <span class="token string">'__main__'</span><span class="token punctuation">:</span>
    <span class="token comment"># 局部引用demo.py，因为只有在当__name__ == '__main__'</span>
    <span class="token comment"># 注册蓝图</span>
    <span class="token keyword">from</span> controller<span class="token punctuation">.</span>demo <span class="token keyword">import</span> <span class="token operator">*</span>
    app<span class="token punctuation">.</span>register_blueprint<span class="token punctuation">(</span>demo<span class="token punctuation">)</span>

    <span class="token keyword">from</span> controller<span class="token punctuation">.</span>user <span class="token keyword">import</span> <span class="token operator">*</span>
    app<span class="token punctuation">.</span>register_blueprint<span class="token punctuation">(</span>user<span class="token punctuation">)</span>

    app<span class="token punctuation">.</span>run<span class="token punctuation">(</span>debug<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span>
</code></pre></div><p>第二步，在module下建一个users.py文件，导入db构建模型类，以及数据库操作方法</p> <div class="language-python extra-class"><pre class="language-python"><code><span class="token keyword">from</span> sqlalchemy <span class="token keyword">import</span> Table<span class="token punctuation">,</span> MetaData

<span class="token keyword">from</span> main <span class="token keyword">import</span> db

<span class="token keyword">class</span> <span class="token class-name">Users</span><span class="token punctuation">(</span>db<span class="token punctuation">.</span>Model<span class="token punctuation">)</span><span class="token punctuation">:</span>
    __table__ <span class="token operator">=</span> Table<span class="token punctuation">(</span><span class="token string">'users'</span><span class="token punctuation">,</span> MetaData<span class="token punctuation">(</span>bind<span class="token operator">=</span>db<span class="token punctuation">.</span>engine<span class="token punctuation">)</span><span class="token punctuation">,</span> autoload<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span>

    <span class="token keyword">def</span> <span class="token function">find_user_by_id</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span>userid<span class="token punctuation">)</span><span class="token punctuation">:</span>
        row <span class="token operator">=</span>db<span class="token punctuation">.</span>session<span class="token punctuation">.</span>query<span class="token punctuation">(</span>Users<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">filter</span><span class="token punctuation">(</span>Users<span class="token punctuation">.</span>userid<span class="token operator">==</span>userid<span class="token punctuation">)</span><span class="token punctuation">.</span>first<span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token keyword">return</span> row
</code></pre></div><p>第三步，生成一个接口，向这个接口输出我们需要的信息</p> <div class="language-python extra-class"><pre class="language-python"><code><span class="token keyword">from</span> module<span class="token punctuation">.</span>users <span class="token keyword">import</span>  Users

<span class="token keyword">from</span>  flask <span class="token keyword">import</span> Blueprint
user<span class="token operator">=</span>Blueprint<span class="token punctuation">(</span><span class="token string">'user'</span><span class="token punctuation">,</span>__name__<span class="token punctuation">)</span>

<span class="token decorator annotation punctuation">@user<span class="token punctuation">.</span>route</span><span class="token punctuation">(</span><span class="token string">'/user'</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">user_demo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    users<span class="token operator">=</span>Users<span class="token punctuation">(</span><span class="token punctuation">)</span>
    row<span class="token operator">=</span>users<span class="token punctuation">.</span>find_user_by_id<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
    <span class="token keyword">return</span> row<span class="token punctuation">.</span>username

</code></pre></div><h3 id="sqlalchemy基础查询"><a href="#sqlalchemy基础查询" class="header-anchor">#</a> SQLAlchemy基础查询</h3> <p>Flask框架本身是最小化Web服务内核，表与表之间的关系，不一定要定义在数据库中，心中有关系就行。
（数据库为了维护主外键关系，会增加额外消耗）。
删除数据时，尽量使用软删除（设置标识），而不是直接硬删除（Delete From）</p> <div class="language-python extra-class"><pre class="language-python"><code><span class="token punctuation">.</span>first<span class="token punctuation">(</span><span class="token punctuation">)</span>  直接返回一行数据对象
<span class="token punctuation">.</span><span class="token builtin">all</span><span class="token punctuation">(</span><span class="token punctuation">)</span> 直接返回包含多条数据对象的列表
<span class="token punctuation">.</span>filter_by<span class="token punctuation">(</span>a<span class="token operator">=</span>b<span class="token punctuation">,</span>x<span class="token operator">=</span>y<span class="token punctuation">)</span>只适用于等值查询，其参数为字典参数的传值方式
<span class="token punctuation">.</span><span class="token builtin">filter</span><span class="token punctuation">(</span><span class="token punctuation">)</span>适用于复杂查询条件的对比，其参数为条件运算
查询过程中，可以使用db<span class="token punctuation">.</span>session的方式进行查询（支持多表），也可以使用Model<span class="token punctuation">.</span>query的方式进行查询（不支持多表），所以优先使用db<span class="token punctuation">.</span>session
 <span class="token keyword">def</span> <span class="token function">find_user_by_id</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span>userid<span class="token punctuation">)</span><span class="token punctuation">:</span>
        row <span class="token operator">=</span>db<span class="token punctuation">.</span>session<span class="token punctuation">.</span>query<span class="token punctuation">(</span>Users<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">filter</span><span class="token punctuation">(</span>Users<span class="token punctuation">.</span>userid<span class="token operator">==</span>userid<span class="token punctuation">)</span><span class="token punctuation">.</span>first<span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token keyword">return</span> row
</code></pre></div><p>基础查询语句</p> <div class="language-python extra-class"><pre class="language-python"><code>result<span class="token operator">=</span>dbsession<span class="token punctuation">.</span>query<span class="token punctuation">(</span>Users<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">all</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
result <span class="token operator">=</span> dbsession<span class="token punctuation">.</span>query<span class="token punctuation">(</span>Users<span class="token punctuation">.</span>userid<span class="token punctuation">,</span>Users<span class="token punctuation">.</span>username<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">all</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
result <span class="token operator">=</span> dbsession<span class="token punctuation">.</span>query<span class="token punctuation">(</span>Users<span class="token punctuation">)</span><span class="token punctuation">.</span>filter_by<span class="token punctuation">(</span>userid<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">,</span>qq<span class="token operator">=</span><span class="token string">'11111111'</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">all</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
result <span class="token operator">=</span> dbsession<span class="token punctuation">.</span>query<span class="token punctuation">(</span>Users<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">filter</span><span class="token punctuation">(</span>or_<span class="token punctuation">(</span>Users<span class="token punctuation">.</span>userid<span class="token operator">==</span><span class="token number">1</span><span class="token punctuation">,</span> Users<span class="token punctuation">.</span>qq<span class="token operator">==</span><span class="token string">'00'</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">all</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment"># select *from users limit 3</span>
result <span class="token operator">=</span> dbsession<span class="token punctuation">.</span>query<span class="token punctuation">(</span>Users<span class="token punctuation">)</span><span class="token punctuation">.</span>limit<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">all</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment">#     select *from users limit 3,1 表示从3开始1条数据</span>
result <span class="token operator">=</span> dbsession<span class="token punctuation">.</span>query<span class="token punctuation">(</span>Users<span class="token punctuation">)</span><span class="token punctuation">.</span>limit<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">.</span>offset<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">all</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
count<span class="token operator">=</span>dbsession<span class="token punctuation">.</span>query<span class="token punctuation">(</span>Users<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">filter</span><span class="token punctuation">(</span>Users<span class="token punctuation">.</span>userid<span class="token operator">&lt;</span><span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">.</span>count<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment"># 去重复 select distinct(qq) from users</span>
result <span class="token operator">=</span>dbsession<span class="token punctuation">.</span>query<span class="token punctuation">(</span>Users<span class="token punctuation">.</span>qq<span class="token punctuation">)</span><span class="token punctuation">.</span>distinct<span class="token punctuation">(</span>Users<span class="token punctuation">.</span>qq<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">all</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment"># 倒序</span>
result <span class="token operator">=</span> dbsession<span class="token punctuation">.</span>query<span class="token punctuation">(</span>Users<span class="token punctuation">)</span><span class="token punctuation">.</span>order_by<span class="token punctuation">(</span>Users<span class="token punctuation">.</span>userid<span class="token punctuation">.</span>desc<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">all</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment"># 模糊查询</span>
result <span class="token operator">=</span> dbsession<span class="token punctuation">.</span>query<span class="token punctuation">(</span>Users<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">filter</span><span class="token punctuation">(</span>Users<span class="token punctuation">.</span>username<span class="token punctuation">.</span>like<span class="token punctuation">(</span><span class="token string">'%w%'</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">all</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment"># 分组,也可以去重 group by</span>
<span class="token comment"># result = dbsession.query(Users).group_by(Users.role).all()</span>
<span class="token comment"># result = dbsession.query(Users).group_by(Users.role).having(Users.userid&gt;2).all()</span>
<span class="token comment"># 聚合函数 min,max,avg,sum</span>
result <span class="token operator">=</span> dbsession<span class="token punctuation">.</span>query<span class="token punctuation">(</span>func<span class="token punctuation">.</span><span class="token builtin">sum</span><span class="token punctuation">(</span>Users<span class="token punctuation">.</span>credit<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span>first<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment"># &gt; &lt; == != in not</span>

<span class="token keyword">print</span><span class="token punctuation">(</span>count<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span>
<span class="token comment"># print(result[0].username)   #[&lt;__main__.Users object at 0x7fb934b9e0d0&gt;]</span>

</code></pre></div></div> <footer class="page-edit" style="display:none;"><!----> <div class="last-updated"><span class="prefix">Last Updated: </span> <span class="time">2022/1/5 下午4:20:07</span></div></footer> <!----> <!----> <!----></main> <!----></div></div></div></div></div><div class="global-ui"><div class="back-to-ceiling" style="right:1rem;bottom:6rem;width:2.5rem;height:2.5rem;border-radius:.25rem;line-height:2.5rem;display:none;" data-v-c6073ba8 data-v-c6073ba8><svg t="1574745035067" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5404" class="icon" data-v-c6073ba8><path d="M526.60727968 10.90185116a27.675 27.675 0 0 0-29.21455937 0c-131.36607665 82.28402758-218.69155461 228.01873535-218.69155402 394.07834331a462.20625001 462.20625001 0 0 0 5.36959153 69.94390903c1.00431239 6.55289093-0.34802892 13.13561351-3.76865779 18.80351572-32.63518765 54.11355614-51.75690182 118.55860487-51.7569018 187.94566865a371.06718723 371.06718723 0 0 0 11.50484808 91.98906777c6.53300375 25.50556257 41.68394495 28.14064038 52.69160883 4.22606766 17.37162448-37.73630017 42.14135425-72.50938081 72.80769204-103.21549295 2.18761121 3.04276886 4.15646224 6.24463696 6.40373557 9.22774369a1871.4375 1871.4375 0 0 0 140.04691725 5.34970492 1866.36093723 1866.36093723 0 0 0 140.04691723-5.34970492c2.24727335-2.98310674 4.21612437-6.18497483 6.3937923-9.2178004 30.66633723 30.70611158 55.4360664 65.4791928 72.80769147 103.21549355 11.00766384 23.91457269 46.15860503 21.27949489 52.69160879-4.22606768a371.15156223 371.15156223 0 0 0 11.514792-91.99901164c0-69.36717486-19.13165746-133.82216804-51.75690182-187.92578088-3.42062944-5.66790279-4.76302748-12.26056868-3.76865837-18.80351632a462.20625001 462.20625001 0 0 0 5.36959269-69.943909c-0.00994388-166.08943902-87.32547796-311.81420293-218.6915546-394.09823051zM605.93803103 357.87693858a93.93749974 93.93749974 0 1 1-187.89594924 6.1e-7 93.93749974 93.93749974 0 0 1 187.89594924-6.1e-7z" p-id="5405" data-v-c6073ba8></path><path d="M429.50777625 765.63860547C429.50777625 803.39355007 466.44236686 1000.39046097 512.00932183 1000.39046097c45.56695499 0 82.4922232-197.00623328 82.5015456-234.7518555 0-37.75494459-36.9345906-68.35043303-82.4922232-68.34111062-45.57627738-0.00932239-82.52019037 30.59548842-82.51086798 68.34111062z" p-id="5406" data-v-c6073ba8></path></svg></div><div class="kanbanniang" data-v-5775ee02><div class="banniang-container" style="display:;" data-v-5775ee02><div class="messageBox" style="right:68px;bottom:190px;display:none;" data-v-5775ee02>
      我是王茂铭谢谢你的关注 
    </div> <div class="operation" style="right:90px;bottom:40px;display:;" data-v-5775ee02><i class="kbnfont kbn-ban-home ban-home" data-v-5775ee02></i> <i class="kbnfont kbn-ban-message message" data-v-5775ee02></i> <i class="kbnfont kbn-ban-close close" data-v-5775ee02></i> <a target="_blank" href="https://vuepress-theme-reco.recoluan.com/views/plugins/kanbanniang.html" data-v-5775ee02><i class="kbnfont kbn-ban-info info" data-v-5775ee02></i></a> <i class="kbnfont kbn-ban-theme skin" style="display:;" data-v-5775ee02></i></div> <canvas id="banniang" width="240" height="352" class="live2d" style="right:90px;bottom:-20px;opacity:0.9;" data-v-5775ee02></canvas></div> <div class="showBanNiang" style="display:none;" data-v-5775ee02>
    看板娘
  </div></div><canvas id="vuepress-canvas-cursor"></canvas><APlayer audio="" fixed="true" mini="true" autoplay="autoplay" theme="#b7daff" loop="loop" order="random" preload="auto" volume="0.2" mutex="true" lrc-type="1" list-max-height="250" storage-name="vuepress-plugin-meting" id="aplayer-fixed"></APlayer></div></div>
    <script src="/vue-press-blog-html/assets/js/app.0c76d487.js" defer></script><script src="/vue-press-blog-html/assets/js/5.12b1c0e9.js" defer></script><script src="/vue-press-blog-html/assets/js/1.6e6d8766.js" defer></script><script src="/vue-press-blog-html/assets/js/21.da88625b.js" defer></script>
  </body>
</html>
